package com.example.demo.leetcode.top100;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _59括号生成
 * @description
 * @date 2023/06/21 14:25
 * <p>
 * ******************************************************
 */
public class _59括号生成 {

    List<String> result = new LinkedList<>();
    StringBuilder trace = new StringBuilder();
    char[] chars = new char[]{'(', ')'};

    public List<String> generateParenthesis(int n) {
        backtrack(n, n, n);
        return result;
    }

    private void backtrack(int n, int left, int right) {
        if (left == 0 && right == 0) {
            result.add(trace.toString());
            return;
        }

        if (left > right) {
            return;
        }


        if (left > 0) {
            trace.append(chars[0]);
            backtrack(n, left - 1, right);
            trace.deleteCharAt(trace.length() - 1);
        }

        if (right > 0) {
            trace.append(chars[1]);
            backtrack(n, left, right - 1);
            trace.deleteCharAt(trace.length() - 1);
        }


    }


    public static void main(String[] args) {
        _59括号生成 s = new _59括号生成();
        System.out.println(s.generateParenthesis(3));
    }

}
